﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace DatFileRead{
    internal class Https{
        // 建议复用一个 HttpClient
        private static readonly HttpClient Http = new HttpClient();
        string authkey, authkeyVer, signType, authAppid, gameBiz, region, lang;
        string? url;
       public Https(string authkey, string authkeyVer, string signType, string authAppid, string gameBiz, string region, string lang) { 
            this.authkey = authkey;
            this.authkeyVer = authkeyVer;
            this.signType = signType;
            this.authAppid = authAppid;
            this.gameBiz = gameBiz;
            this.region = region;
            this.lang = lang;
            
        }

        public Https(string url) {
           
            this.url = url;
        }

        public async Task Get() { 
            var response =  Http.GetStringAsync(url);
            Console.WriteLine(response);
            return ;
        }
        

       public  async Task Start()
        {
            // 将下面参数替换为你链接中的值（authkey直接用链接里的原样，勿二次编码）
            /*string authkey = "Xcp7fiQilsmA6mLNi9XZQaFgkwq3nUIBVmGikDxAvSf5eqcwqfcVxqaDgsStNOXsTvo5u25KwGZAQdlwTbtU9bmVGn8OUtc0YKX%2BHXh8qugk1eP57Y%2BPm8uNEMPcZjujCaaMmNjb7oc0BzGWekHfgdemZei7RWRNCSUVNfcfCUL2sTGbZpi49GjWBezDn%2F11PKnzNTllIzo%2BM2Wp3AzHZz%2FChFNjuh7oMzOd0Shm5VEeBo1gh8kFzDSTtpeF3Q2deIXbukq5vnVBp7GjRSzKxNmQKzi37YqzuzTLVm%2FPT2sPaNFYjtOKU5WbxUKLnmAkirYWFoSVMRCS963XjQah06rQS9vWGlPoLurVV3wbzwUQFaKoJKMpwjiqoRKS4LM1x%2FrkpOjWo9czmJyeZn14oczkcqF6oqsLLnq1QMHFxm5%2FTZx3EH%2FRupvXFTVS77Vxrjt7SyLyKVN%2FMIDel97echyXnUuoiwZYJDkuUWNV%2BKTOX4PHFVTGrLLN6LUKa8eFQmjerXCLusp6nqvHBxF1kMJMiJQrzfk4P8on98I%2F%2FFq2Bkq1zbBm%2FZA3fNvOABv7NLGamb0Qs%2Fsqr3mkRCoobZ9DkYCFlX95J7yDoeYf1vzQbq6Um2vjlJlYlm2YA%2FJAWRp3okrufStMq1Mi%2BB%2FcbDiMoO2fgUQEOVSqa3zDl9I%3D\r\n";
            string authkeyVer = "1";
            string signType = "2";
            string authAppid = "webview_gacha";

            string gameBiz = "hkrpg_cn";
            string region = "prod_gf_cn";
            string lang = "zh-cn";*/

            // 设置请求头（提高成功率）
            Http.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
            Http.DefaultRequestHeaders.TryAddWithoutValidation("Origin", "https://webstatic.mihoyo.com");
            Http.DefaultRequestHeaders.TryAddWithoutValidation("Referer", "https://webstatic.mihoyo.com/hkrpg/event/e20211215gacha-v2/index.html");

            // 示例1：单页打印（以角色活动池 gacha_type=11 为例）
            string singlePageJson = await FetchPageAsync(
                authkey, authkeyVer, signType, authAppid,
                gameBiz, region, lang,
                gachaType: "11", page: 1, size: 20, endId: "0"
            );
            Console.WriteLine("—— 单页 JSON ——");
            
            GachaLogResponse? res = JsonSerializer.Deserialize<GachaLogResponse>(singlePageJson);
            if (res == null || res.Data == null) return;
            if (res.Data.List == null) return;
            List<GachaLogItem> variable = res.Data.List;
            Console.WriteLine($"名称\t\t\t\t等级\t\t\t\t类型");
            foreach (var data in variable) {
                if(Convert.ToInt16(data.RankType) >= 4)
                    if(data.Name.Length <= 2)
                    Console.WriteLine($"{data.Name}\t\t\t\t{data.RankType}\t\t\t\t{data.ItemType}");
                else if(data.Name.Length >=3)
                        Console.WriteLine($"{data.Name}\t\t\t{data.RankType}\t\t\t\t{data.ItemType}");
            }
            
         

            // 示例2：全量分页打印（直到该池数据结束）
            Console.WriteLine("—— 全量分页 JSON（逐页打印） ——");
            await FetchAllPagesAndPrintAsync(
                authkey, authkeyVer, signType, authAppid,
                gameBiz, region, lang,
                gachaType: "11", size: 20
            );
        }

        // 拉取单页并返回 JSON 字符串
        private static async Task<string> FetchPageAsync(
            string authkey, string authkeyVer, string signType, string authAppid,
            string gameBiz, string region, string lang,
            string gachaType, int page, int size, string endId)
        {
            // 国服常用域名（其中一个不可用时可切换另一个）
            string[] bases = {
            "https://public-operation-hkrpg.mihoyo.com"
        };

            foreach (var baseUrl in bases)
            {
                var url =
                    $"{baseUrl}/common/gacha_record/api/getGachaLog" +
                    $"?authkey={authkey}" +
                    $"&authkey_ver={authkeyVer}" +
                    $"&sign_type={signType}" +
                    $"&auth_appid={authAppid}" +
                    $"&game_biz={gameBiz}" +
                    $"&region={region}" +
                    $"&lang={lang}" +
                    $"&gacha_type={gachaType}" +
                    $"&page={page}" +
                    $"&size={size}" +
                    $"&end_id={endId}";

                try
                {
                    var resp = await Http.GetAsync(url);
                    if (resp.IsSuccessStatusCode)
                        return await resp.Content.ReadAsStringAsync();
                }
                catch
                {
                    // 忽略异常，尝试下一个域名
                }
            }

            throw new Exception("两个域名都不可用或网络异常。");
        }

        // 自动翻页并逐页打印 JSON；直到列表为空或接口报错
        static async Task FetchAllPagesAndPrintAsync(
            string authkey, string authkeyVer, string signType, string authAppid,
            string gameBiz, string region, string lang,
            string gachaType, int size)
        {
            string? endId = "0";
            int page = 1;
            Console.WriteLine($"名称\t\t\t\t等级\t\t\t\t类型");
            while (true)
            {if (endId == null) return;
                string json = await FetchPageAsync(
                    authkey, authkeyVer, signType, authAppid,
                    gameBiz, region, lang,
                    gachaType, page, size, endId
                );

                //Console.WriteLine($"--- gacha_type={gachaType} page={page} end_id={endId} ---");
                //Console.WriteLine(json);
                GachaLogResponse? res = JsonSerializer.Deserialize<GachaLogResponse>(json);
                if (res == null || res.Data == null) return;
                if (res.Data.List == null) return;
                List<GachaLogItem> variable = res.Data.List;
                
                foreach (var data in variable)
                {
                    if(Convert.ToInt16(data.RankType) < 4) continue;


                    if (data.Name.Length <= 3)
                    {
                        Console.WriteLine($"{data.Name}\t\t\t\t{data.RankType}\t\t\t\t{data.ItemType}");
                    }
                    else if (data.Name.Length > 3) {
                        Console.WriteLine($"{data.Name}\t\t\t{data.RankType}\t\t\t\t{data.ItemType}");
                    }
                                
                    
                        
                }

                var doc = JsonDocument.Parse(json);
                var root = doc.RootElement;

                int retcode = root.GetProperty("retcode").GetInt32();
                if (retcode != 0)
                {
                    string? msg = root.TryGetProperty("message", out var m) ? m.GetString() : "unknown error";
                    Console.WriteLine($"接口返回错误：retcode={retcode}, message={msg}");
                    break;
                }

                var list = root.GetProperty("data").GetProperty("list");
                int count = list.GetArrayLength();
                if (count == 0)
                {
                    Console.WriteLine("分页结束：当前池无更多记录。");
                    break;
                }

                // 下一页游标：取上一页最后一条的 id
                endId = list[count - 1].GetProperty("id").GetString();
                page++; // 或者固定 page=1，仅用 end_id 做游标

                // 轻微节流，避免过快请求
                await Task.Delay(300);
            }
        }
    }

    public class GachaLogResponse
    {
        [JsonPropertyName("retcode")]
        public int? Retcode { get; set; }

        [JsonPropertyName("message")]
        public string? Message { get; set; }

        [JsonPropertyName("data")]
        public GachaLogData? Data { get; set; }
    }

    public class GachaLogData
    {
        // 注意：示例 JSON 中的 page/size 是字符串
        [JsonPropertyName("page")]
        public string? Page { get; set; }

        [JsonPropertyName("size")]
        public string? Size { get; set; }

        [JsonPropertyName("list")]
        public List<GachaLogItem>? List { get; set; }

        [JsonPropertyName("region")]
        public string? Region { get; set; }

        [JsonPropertyName("region_time_zone")]
        public int RegionTimeZone { get; set; }

        // 该字段结构不固定，这里用 JsonElement 占位
        [JsonPropertyName("list_v2")]
        public List<JsonElement>? ListV2 { get; set; }
    }

    public class GachaLogItem
    {
        [JsonPropertyName("uid")]
        public string? Uid { get; set; }

        [JsonPropertyName("gacha_id")]
        public string? GachaId { get; set; }

        [JsonPropertyName("gacha_type")]
        public string? GachaType { get; set; }

        [JsonPropertyName("item_id")]
        public string? ItemId { get; set; }

        [JsonPropertyName("count")]
        public string? Count { get; set; }

        // 示例为 "yyyy-MM-dd HH:mm:ss" 字符串，非 ISO 8601，这里用 string
        [JsonPropertyName("time")]
        public string? Time { get; set; }

        [JsonPropertyName("name")]
        public string? Name { get; set; }

        [JsonPropertyName("lang")]
        public string? Lang { get; set; }

        [JsonPropertyName("item_type")]
        public string? ItemType { get; set; }

        [JsonPropertyName("rank_type")]
        public string? RankType { get; set; }

        [JsonPropertyName("id")]
        public string? Id { get; set; }
    }

}

